/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once

#include "hhdHashFunctions.hpp"
#include "hhdEqualityFunctions.hpp"
#include "hhdSingle.hpp"

namespace hhd
{
    /**
    * HashSet is an unordered set of objects, implemented as a hash table using linear probing.
    */
    template <typename Key> class HashSet
    {
    public:
        /**
        * Default constructor with initial size of 100
        */

        HashSet()
			: _load_factor(0.5f)
			, _size(32)
			, _elements(0)
        {
            _hash = &HashFunctions::primitive_hash<Key>;
            _equals = &EqualityFunctions::equals<Key>;

            _data = new Single<Key>*[_size];

            // null out data buffer
            memset(_data, 0, sizeof(Single<Key>*) * _size);
        }

        /**
        * Constructor which sets initial size.
        * @param initial_size The initial size of our internal buffer
        */
        HashSet(size_t initial_size)
			: _load_factor(0.5f)
			, _size(initial_size)
			, _elements(0)
        {
			HHD_ASSERT(initial_size > 0);

			_hash = &HashFunctions::primitive_hash<Key>;
			_equals = &EqualityFunctions::equals<Key>;

            _data = new Single<Key>*[_size];

            // null out data bufffer
            memset(_data, 0, sizeof(Single<Key>*) * _size);
        }

        /**
        * Copy constructor
        * @param other The hashset to copy.
        */
        HashSet(const HashSet& other)
        {
            _hash = other._hash;
            _equals = other._equals;

            _size = other._size;
            _elements = other._elements;

            _data = new Single<Key>*[_size];

            for(size_t k = 0; k < _size; k++)
            {
                if(other._data[k])
                {
                    _data[k] = new Single<Key>(*(other._data[k]));
                }
                else
                {
                    _data[k] = NULL;
                }
            }
        }

        HashSet(size_t initial_size,
                uint32_t (*in_hash)(const Key&),
                bool (*in_equals)(const Key&, const Key&))
            : _load_factor(0.5f)
            , _size(initial_size)
            , _elements(0)
        {
            HHD_ASSERT(initial_size > 0);

            _hash = in_hash;
            _equals = in_equals;

            _data = new Single<Key>*[_size];

            // null out data buffer
            memset(_data, 0, sizeof(Single<Key>*) * _size);
        }

        ~HashSet()
        {
            for(size_t k = 0; k < _size; k++)
			{
                if(_data[k] != NULL)
                {
                    delete _data[k];
                }
			}
            delete[] _data;
        }

        /**
        * Determine if given key is in the set.
        * @param in_key Key to check for
        * @return true if Key is in set, false if not
        */
        bool contains(Key in_key) const
        {
            for(size_t index = _hash(in_key) % _size; _data[index] != NULL; index = (index + 1) % _size)
			{
                if(_equals(_data[index]->first, in_key))
                {
                    return true;
                }
			}
            return false;
        }

        /**
        * Add a key to the set.
        * @param in_key Key to add to set.
        * @param returns true if added, false if not added because key already in set.
        */
        bool add(const Key& in_key)
        {
            // see if we need to make it bigger
            if(_size * _load_factor <= _elements)
            {
                resize();
            }

            size_t index;

            for(index = _hash(in_key) % _size; _data[index] != NULL; index = (index + 1) % _size)
			{
                if(_equals(_data[index]->first, in_key))
                {
                    return false;
                }
			}
            _data[index % _size] = new Single<Key>(in_key);
            _elements++;
            return true;
        }

        /**
        * Remove a given key from the set.  Sometimes this is expensive, and must rebuild the entire set.
        * @param in_key Key to remove
        * @return True if removed, False if it was not in the set
        */
        bool remove(const Key& in_key)
        {
            if(!contains(in_key))
            {
                return false;
            }

            uint32_t key_index = _hash(in_key) % _size;

            if(_equals(_data[key_index]->first, in_key) && _data[(key_index + 1) % _size] == NULL )
            {
                delete _data[key_index];
                // if we are here, no linear probing happened on this key, so we can just remove the key
                _data[key_index] = NULL;
                _elements--;
                return true;
            }
            Single<Key>** new_data = new Single<Key>*[_size];
            memset(new_data, 0, sizeof(Single<Key>*) * _size);

            for(size_t i = 0; i < _size; i++)
            {
                Single<Key>* s = _data[i];
                if(s)
                {
                    if(!_equals(s->first, in_key))
                    {
                        unsigned int index = _hash(s->first);
                        while(new_data[index % _size] != NULL)
                        {
                            index++;
                        }
                        new_data[index % _size] = s;
                    }
                    else
                    {
                        delete s;
                    }
                }
            }

            delete[] _data;
            _data = new_data;
            _elements--;
            return true;
        }

        /**
        * Clears the hashset
        */
        void clear()
        {
            // delete singles
            for(size_t k = 0; k < _size; k++)
			{
                if(_data[k])
                {
                    delete _data[k];
                }
			}

            memset(_data, 0, sizeof(Single<Key>*) * _size);
            _elements = 0;
        }

        /**
        * Returns the size of the
        */
        size_t size() const
        {
            return _elements;
        }

    private:
        /** doubles the size of the buffer */
        void resize()
        {
            size_t new_size = _size * 2;
            Single<Key>** new_data = new Single<Key>*[new_size];

            // zero out the new buffer
            memset(new_data, 0, sizeof(Single<Key>*) * new_size);

            for(size_t k = 0; k < _size; k++)
            {
                Single<Key>* s = _data[k];
                if(s)
                {
                    unsigned int index = _hash(s->first);
                    while(new_data[index % new_size] != NULL)
                    {
                        index++;
                    }
                    new_data[index % new_size] = s;
                }
            }

            delete[] _data;
            _data = new_data;
            _size = new_size;
        }

        // hash function
        uint32_t (*_hash)(const Key&);

        // equals function
        bool (*_equals)(const Key&, const Key&);

        Single<Key>** _data;

        float _load_factor;
        size_t _size;
        size_t _elements;
    };
}